<template>
  <el-form ref="form" :rules="rules" :model="fruit" label-width="80px" style="width: 600px" class="fruitFromClass">
    <el-form-item label="水果ID">
      <el-input v-model="fruit.id" readonly></el-input>
    </el-form-item>
    <el-form-item label="名称" prop="name">
      <el-input v-model="fruit.name"></el-input>
    </el-form-item>
    <el-form-item label="销量" prop="sale">
      <el-input v-model.number="fruit.sale"></el-input>
    </el-form-item>
    <el-form-item label="图片" prop="icon">
      <el-input v-model="fruit.icon"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit('form')">立即修改</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'EditFruit',
  data () {
    return {
      fruit: {
        name: '',
        sale: '',
        icon: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入水果名称', trigger: 'blur' }
        ],
        sale: [
          { required: true, message: '请输入销量', trigger: 'blur' },
          { type: 'number', message: '销量必须为数字值' }
        ],
        icon: [
          { required: true, message: '请输入图片链接', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.showCurrentFruit()
  },
  methods: {
    async showCurrentFruit () {
      console.log(this.$route.query.id)
      const id = this.$route.query.id
      const { data: res } = await this.axios.get('/fruit/find/' + id)
      console.log('getFruit', res)
      if (res) {
        this.fruit = res
      }
    },
    onSubmit (form) {
      this.$refs[form].validate(async (valid) => {
        const { data: res } = await this.axios.put('/fruit/update', this.fruit)
        if (res) {
          this.$alert(this.fruit.name + '修改成功！', '修改数据', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message.success('编辑成功')
              this.$router.push('/fruitlist')
            }
          })
        } else {
          this.$message.error('编辑失败！！！')
        }
      })
    },
    cancel () {
      this.$router.push('/fruitlist')
    }
  }
}
</script>

<style  scoped>
  .fruitFromClass{
    text-align: center;
    margin: 0 auto;
  }
</style>
